package logic

import (
	"061/Sgame/constant"
	"061/Sgame/db"
	"061/Sgame/net"
	"061/Sgame/server/common"
	"061/Sgame/server/game/gameConfig"
	"061/Sgame/server/game/model"
	"061/Sgame/server/game/model/data"
	"061/Sgame/utils"
	"log"
	"time"
)

var RoleService = &roleService{}

type roleService struct {
}

func (r *roleService) EnterServer(uid int, resobj *model.EnterServerRsp, req *net.WsMsgReq) error {
	tx := db.GormDB.Begin()
	defer func() {
		if r := recover(); r != nil {
			tx.Rollback()
		}
	}()
	req.Context.Set("dbSession", tx)
	var role data.Role
	err := tx.Where("uid=?", uid).First(&role).Error
	if err != nil {
		//无角色数据
		//log.Println("角色不存在。",err)
		//rsp.Body.Code=constant.RoleNotExist
		return common.New(constant.RoleNotExist, "角色不存在")
	} else {
		//有角色
		//rsp.Body.Code=constant.OK
		//rsp.Body.Msg=resobj
		rid := role.RId
		roleRes := data.RoleRes{}
		//查角色下的资源
		err = tx.Where("rid=?", rid).First(&roleRes).Error
		if err != nil {
			//没查到角色资源，初始化角色资源
			roleRes.RId = rid
			roleRes.Gold = gameConfig.Base.Role.Gold
			roleRes.Decree = gameConfig.Base.Role.Decree
			roleRes.Grain = gameConfig.Base.Role.Grain
			roleRes.Iron = gameConfig.Base.Role.Iron
			roleRes.Stone = gameConfig.Base.Role.Stone
			roleRes.Wood = gameConfig.Base.Role.Wood
			//把数据插入
			err = tx.Create(&roleRes).Error
			if err != nil {
				tx.Rollback()
				//log.Println("创建角色资源出错。",err)
				//rsp.Body.Code=constant.DBError
				return common.New(constant.DBError, "创建角色资源出错")
			}
		}
		resobj.RoleRes = roleRes.ToModel().(model.RoleRes)
		resobj.Role = role.ToModel().(model.Role)
		//根据rid重新生成token
		token, _ := utils.Award(rid)
		resobj.Token = token
		resobj.Time = time.Now().UnixNano() / 1e6

		req.Conn.SetProperty("role", &role)
		//初始化玩家属性
		err := RoleAttrService.TryCreate(role.RId, req)
		if err != nil {
			return err
		}
		//初始化城池
		if err := RoleCityService.InitCity(rid, role.NickName, req); err != nil {
			return err
		}
	}

	err = tx.Commit().Error
	if err != nil {
		return common.New(constant.DBError, "事务提交出错")
	}
	net.Mgr.RoleEnter(req.Conn, role.RId)
	return nil
}
func (r *roleService) GetRoleRes(rid int) (model.RoleRes, error) {
	roleRes := &data.RoleRes{}
	err := db.GormDB.Where("rid=?", rid).First(roleRes).Error
	if err != nil {
		log.Println("查询角色资源出错", err)
		return model.RoleRes{}, common.New(constant.DBError, "角色资源不存在")
	}
	return roleRes.ToModel().(model.RoleRes), nil
}

func (r *roleService) Get(rid int) *data.Role {
	role := &data.Role{}
	err := db.GormDB.Model(role).Where("rid=?", rid).First(role).Error
	if err != nil {
		log.Println("无角色", err)
		return nil
	}
	return role
}
